;
(function(window, jQuery){
	var ROLE = 'cascadeAjaxMenu';
	var Support = {
		disableNext: function(pElmCurr){
			var elmNext = pElmCurr.next('[role="'+ROLE+'"]');
			if( elmNext.length>0 ) {
				Support.disableNext(elmNext);
				elmNext.prop('disabled', true);
			}
		},
		createNextHtml: function(pData){
			var arrHtml = [];
			if(jQuery.isPlainObject(pData)){
				for( var key in pData ){
					if( pData.hasOwnProperty(key) ) arrHtml.push('<option value="'+key+'">'+pData[key]+'</option>');
				}
			}else{
				for(var i= 0,ln=pData.length; i<ln; i++){
					var item = pData[i];
					arrHtml.push('<option value="'+item.value+'">'+item.text+'</option>');
				}
			}
			return jQuery(arrHtml.join(''));
		},
		enableNext: function(pElmCurr){
			pElmCurr.next('[role="'+ROLE+'"]').prop('disabled', false);
		},
		setPreloading: function(elmContainer){
			elmContainer.append('<span class="cmpt-preloading-16"></span>');
		},
		removePreloading: function(elmContainer){
			elmContainer.find('.cmpt-preloading-16').remove();
		}
	};
	var CascadeAjaxMenu = function(pElmSelGroup){
		'use strict';
		var ajax = null;
		jQuery.each(pElmSelGroup, function(idx, select){
			var elmSel = jQuery(select),
				elmContainer = elmSel.parents('td');
			elmSel.on('change', function(){
				var elmNext = elmSel.next('[role="'+ROLE+'"]'),
					strValue = elmSel.val(),
					strUrl = elmSel.attr('data-url');

				if( elmNext.length == 0 || !strUrl || strValue=='-1') return;

				Support.disableNext(elmSel);
				// AJAX查询
				var data = {};
				data[elmSel.attr('data-query_name')] = strValue;
				if( ajax ) { ajax.abort(); ajax = null; }
				Support.setPreloading(elmContainer);
				ajax = jQuery.ajax(strUrl, {
					data: data,
					dataType: 'json',
					type: 'GET',
					success: function(resp){
						if( resp.status == 0) return;
						var elmSelectHtml = Support.createNextHtml(resp.data);
						elmNext.html(elmSelectHtml);
						elmNext.prop('disabled', false);
						elmNext.focus().blur();// 触发一次验证
						elmSel.removeClass('field-inputError');
					},
					error: function(){},
					complete: function(){
						Support.removePreloading(elmContainer);
						ajax = null;
					},
					abort: function(){
						ajax = null;
					}
				});
			});
		});
	};
	CascadeAjaxMenu.prototype.constructor = CascadeAjaxMenu;

	window.CascadeAjaxMenu = CascadeAjaxMenu;
})(window, jQuery);

